#!/usr/bin/env bash

# FileName      : back_jira.sh
# Last-modified : 2024-12-19 08:12
# Author        : jack.zang
#!/bin/bash

# 定义变量
LOCAL_BACKUP_DIR="/data2/backup/jhhl/jira"
JIRA_DATA_BACKUP_DIR="$LOCAL_BACKUP_DIR/data"
MYSQL_BACKUP_DIR="$LOCAL_BACKUP_DIR/mysql"
REMOTE_HOST="192.168.11.226"
REMOTE_USER="root"  # 替换为远程主机的用户名
REMOTE_BACKUP_DIR="/data/backups/jira"
YESTERDAY=$(date -d "yesterday" +%Y_%m_%d)
MYSQL_DB="jiradb"
MYSQL_USER="root"  # 替换为MySQL数据库用户
MYSQL_PASSWORD="xxxxx"  # 替换为MySQL数据库密码
MYSQL_HOST="192.168.9.216"  # MySQL数据库所在的IP地址

# 函数: 保留指定目录下的最新N个备份文件，删除其余旧备份文件
retain_latest_files() {
    local dir=$1
    local num_to_keep=$2
    local pattern="jira-backup-*.tar.gz"  # 或者对于 MySQL 备份，可以是 "*.sql.gz"

    # 切换到目标目录并执行清理
    cd "$dir" || return

    # 获取匹配模式的文件列表（按修改时间排序），并删除多余的旧文件
    ls -t $pattern 2>/dev/null | tail -n +$((num_to_keep + 1)) | xargs rm -f --
}

# 创建备份目录（如果它们不存在）
mkdir -p "$JIRA_DATA_BACKUP_DIR" "$MYSQL_BACKUP_DIR"

# 找到昨天的备份文件并复制到本地
# 使用 scp 和 find 命令来查找并复制昨天的备份文件，允许时间部分存在
BACKUP_FILES=$(ssh "$REMOTE_USER@$REMOTE_HOST" "find $REMOTE_BACKUP_DIR -name 'jira-backup-$YESTERDAY-*.tar.gz'")

if [ -n "$BACKUP_FILES" ]; then
    for BACKUP_FILE in $BACKUP_FILES; do
        scp "$REMOTE_USER@$REMOTE_HOST:$BACKUP_FILE" "$JIRA_DATA_BACKUP_DIR/"
    done
else
    echo "No backup file found for yesterday."
    exit 1
fi

# 确保只保留最近的15个JIRA数据备份文件
retain_latest_files "$JIRA_DATA_BACKUP_DIR" 15

# 直接在本地备份远程 MySQL 数据库
MYSQL_BACKUP_NAME="$MYSQL_DB-$(date +%Y_%m_%d).sql.gz"
mysqldump --column-statistics=0 -h "$MYSQL_HOST" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DB" | gzip > "$MYSQL_BACKUP_DIR/$MYSQL_BACKUP_NAME"

# 检查 mysqldump 是否成功执行
if [ $? -eq 0 ]; then
    echo "MySQL backup created successfully: $MYSQL_BACKUP_DIR/$MYSQL_BACKUP_NAME"
    
    # 确保只保留最近的15个MySQL备份文件
    retain_latest_files "$MYSQL_BACKUP_DIR" 15
    
else
    echo "Error: Failed to create MySQL backup."
    exit 1
fi

echo "Backup process completed."